﻿<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title>websocket client</title>
    <style type="text/css">
        body {
            background-color: #000000;
            color: #ffffff;
            font-size: 12px;
        }
        ul {
            list-style:decimal;
        }
    </style>
    <script type="text/javascript" src="jquery-2.1.1.js"></script>
    <script type="text/javascript">

        //webSocket对像
        var webSocket = { n: 1,maxloglength:1000,logs : []  };
 
       

    //开始
    webSocket.start = function () {
        webSocket.n++;
        var inc = document.getElementById('incomming');
        var nx = document.getElementById('nx');
        var wsImpl = window.WebSocket || window.MozWebSocket;
        var form = document.getElementById('sendForm');
        var input = document.getElementById('sendText');
        inc.innerHTML = "";
        inc.innerHTML += "connecting to server ..<br/>";

 

        // create a new websocket and connect
        window.ws = new wsImpl('ws://192.168.1.105:8118/');

        // when data is comming from the server, this metod is called
        ws.onmessage = function (evt) {
            var logdiv = $('#logs');
            if (webSocket.logs.length > webSocket.maxloglength)
            {
                //删除原素自身
                webSocket.logs[0].remove();
                //就是删除下标为1的数组元素。
                webSocket.logs.splice(0, 1);
            }
                var obj = $("<li>" + evt.data + "</li>");
                webSocket.logs.push(obj);
                logdiv.prepend(obj);
         };

        // when the connection is established, this method is called
        ws.onopen = function () {
            inc.innerHTML += '.. connection open<br/>';
        };

        // when the connection is closed, this method is called
        ws.onclose = function () {
            inc.innerHTML += '.. connection closed<br/>';
            inc.innerHTML += "第" + webSocket.n + '次2秒后重新开始联接...<br/>';
            nx.innerHTML = webSocket.n;
            window.ws.close();
            delete wsImpl;
            delete window.ws;
            setTimeout(webSocket.start, 2000);
        }

        form.addEventListener('submit', function (e) {
            e.preventDefault();
            var val = input.value;
            ws.send(val);
            input.value = "";
        });

    }
    window.onload = webSocket.start;
    </script>

</head>
<body>
    <form id="sendForm">
        <input id="sendText" placeholder="Text to send" /><button onclick="window.ws.send( Math.random());">发送数据</button>
    </form>
    <pre id="incomming"></pre>
    <ul id="logs"></ul>
    <pre id="nx"></pre>
</body>
</html>
